package com.rzico.sbl.ui.report.driver

import android.os.Bundle
import android.os.PersistableBundle
import android.widget.TextView
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapOptions
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.*
import com.amap.api.setCameraChangeListener
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityDriverStationMapBinding
import com.rzico.sbl.model.MasterData
import com.rzico.sbl.viewmodel.ReportStationViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.bottomHide
import com.xinnuo.common.helper.bottomShow
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showBottomPhoneDialog
import com.xinnuo.common_ui.utils.subscribeByFinally


class DriverStationMapActivity : BaseActivity(R.layout.activity_driver_station_map) {

    private val mBinding by lazy { ActivityDriverStationMapBinding.bind(getRootView()) }

    override fun getViewModel() = get<ReportStationViewModel>()

    private lateinit var mOverlay: MultiPointOverlay
    private var mBounds: LatLngBounds? = null

    override fun initData() {
        initTitle(title = "水站分布图")

        mBinding
            .stationBottom
            .bottomHide(
                dpValue = 50f,
                duration = 50
            )

        initAmap()
        initOverlay()
    }

    private fun initAmap() {
        mBinding
            .stationMap
            .map
            .apply {
                uiSettings.apply {
                    isZoomControlsEnabled = false     //缩放按钮，默认打开
                    isCompassEnabled = false          //指南针，默认不显示
                    isMyLocationButtonEnabled = false //定位按钮
                    isScaleControlsEnabled = true     //比例尺
                    isScrollGesturesEnabled = true    //滑动手势
                    isZoomGesturesEnabled = true      //缩放手势
                    isRotateGesturesEnabled = true    //旋转手势
                    isTiltGesturesEnabled = true      //倾斜手势
                    logoPosition = AMapOptions.LOGO_POSITION_BOTTOM_RIGHT //地图logo显示在右下方
                }

                mapType = AMap.MAP_TYPE_NAVI   //导航地图模式
                isTrafficEnabled = false       //实时交通状况
                showBuildings(true)            //显示3D楼块
                showMapText(true)              //显示底图文字
                showIndoorMap(true)            //设置是否显示室内地图
                isMyLocationEnabled = false    //触发定位并显示定位层

                // 自定义地图
                setCustomMapStyle(
                    CustomMapStyleOptions().apply {
                        isEnable = true
                        styleData = getByteFromAssets("style.data")
                        styleExtraData = getByteFromAssets("style_extra.data")
                    }
                )

                // 地图加载完成监听
                setOnMapLoadedListener { getData() }

                // 地图状态的监听
                setCameraChangeListener {
                    onCameraChange {
                        mBinding
                            .stationBottom
                            .bottomHide(50f)
                    }
                }

                // 海量点击事件监听
                setOnMultiPointClickListener {
                    mBinding
                        .stationBottom
                        .bottomShow()

                    updateBottom(it.`object` as MasterData)
                    true
                }

                // 默认显示郑州经纬度
                moveCamera(
                    CameraUpdateFactory.newLatLng(
                        LatLng(34.7466, 113.625367)
                    )
                )
            }
    }

    private fun initOverlay() {
        mOverlay = mBinding.stationMap.map
            .addMultiPointOverlay(
                MultiPointOverlayOptions()
                    .anchor(0.5f, 0.9f)
                    .icon(
                        BitmapDescriptorFactory.fromView(
                            inflate<TextView>(R.layout.layout_marker)
                                .apply {
                                    setBackgroundResource(R.mipmap.icon_report_n_07)
                                }
                        )
                    )
            )
    }

    override fun initListener() {
        mBinding.apply {
            stationCall.oneClick {
                stationPhone
                    .content
                    .notEmpty {
                        showBottomPhoneDialog(this)
                    }
            }
        }
    }

    /**
     * 更新底部显示
     */
    private fun updateBottom(data: MasterData) {
        mBinding.apply {
            stationImg.loadCircleImage(
                data.logo,
                R.mipmap.default_user
            )

            stationTitle.text = data.name
            stationName.text = data.linkman.orEmpty("无")
            stationPhone.text = data.telephone.orEmpty()
            stationAdress.text = data.address
        }
    }

    /**
     * 水站分布列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .stationLayoutList()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { list ->
                    mList.clear()
                    mList.addItems(list)

                    moveToBounds()

                    mOverlay.apply {
                        items = mList.map {
                            it as MasterData

                            MultiPointItem(
                                LatLng(
                                    it.lat.doubleValue,
                                    it.lng.doubleValue
                                )
                            ).apply { `object` = it }
                        }
                        setEnable(true)
                    }
                }
            )
    }

    /**
     * 动画显示区域坐标
     */
    private fun moveToBounds() {
        if (mBounds == null) {
            mBounds = LatLngBounds
                .Builder()
                .apply {
                    mList.forEach {
                        it as MasterData
                        include(
                            LatLng(
                                it.lat.doubleValue,
                                it.lng.doubleValue
                            )
                        )
                    }
                }
                .build()

            mBinding
                .stationMap
                .map
                .animateCamera(
                    CameraUpdateFactory.newLatLngBounds(mBounds, 150)
                )
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mBinding.stationMap.onCreate(savedInstanceState)
    }

    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState, outPersistentState)
        // onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mBinding.stationMap.onSaveInstanceState(outState)
    }

    override fun onResume() {
        super.onResume()
        // onResume时执行mMapView.onResume ()，重新绘制加载地图
        mBinding.stationMap.onResume()
    }

    override fun onPause() {
        super.onPause()
        // onPause时执行mMapView.onPause ()，暂停地图的绘制
        mBinding.stationMap.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        // onDestroy时执行mMapView.onDestroy()，销毁地图
        mBinding.stationMap.onDestroy()
    }

}